import { computed, ref } from 'vue'
import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import dayjs from 'dayjs'
export function usrObserve (apifn) {
  const target = ref(null)
  const { stop } = useIntersectionObserver(
    target,
    ([{ isIntersecting }], observerElement) => {
      // console.log(isIntersecting, observerElement)
      if (isIntersecting) {
        // 出现在可视区 调用接口获取组件内容
        apifn()
        // 当出现在可视区内 停止监听
        stop()
      }
    }
  )
  return target
}

export function useCountDown (startCount) {
  const time = ref(0)
  // 准备一个计算属性 基于原来的数字 解析成xx分 xx秒
  const countTimes = computed(() => {
    return dayjs.unix(time.value).format('mm分ss秒')
  })
  const start = (timer) => {
    console.log(timer)
    time.value = timer || startCount || 60
    resume()
  }
  const { pause, resume } = useIntervalFn(() => {
    /* your function */
    if (time.value <= 0) return pause()
    time.value--
  }, 1000)

  return {
    pause,
    resume,
    start,
    time,
    countTimes
  }
}
